package com.wtwd.campus.jdzc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.entity.Student;
import com.wtwd.campus.jdzc.common.Constant;
import com.wtwd.campus.jdzc.common.RespCode;
import com.wtwd.campus.jdzc.common.RespEntity;
import com.wtwd.campus.jdzc.dao.*;
import com.wtwd.campus.jdzc.entity.DeviceInfo;
import com.wtwd.campus.jdzc.entity.JdzcUser;
import com.wtwd.campus.jdzc.entity.JdzcUserStudentPermission;
import com.wtwd.campus.jdzc.service.JdzcService;
import com.wtwd.campus.service.RedisService;
import com.wtwd.campus.utils.CommandSendUtils;
import com.wtwd.campus.utils.Tools;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.wtwd.campus.utils.CommandNumberUtil.getCurTime;

/**
 * @author mjy
 * @date 2022/02/14
 * @description
 */
@Service
public class JdzcServiceImpl implements JdzcService {

    private static final Logger logger = LoggerFactory.getLogger(JdzcServiceImpl.class);

    @Autowired
    private JdzcUserMapper jdzcUserMapper;

    @Autowired
    private JdDeviceInfoMapper jdDeviceInfoMapper;

    @Autowired
    private JdzcStudentMapper jdzcStudentMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private JdzcTeacherMapper teacherMapper;

    @Autowired
    private JdzcUserStudentPermissionMapper jdzcUserStudentPermissionMapper;

    @Autowired
    private CommandSendUtils commandSendUtils;

    @Override
    public JdzcUser getUserInfoByPhone(String phone) {
        return jdzcUserMapper.getUserInfoByPhone(phone);
    }

    @Override
    public JdzcUser createUser(String phone) {
        JdzcUser jdzcUser = new JdzcUser();
        jdzcUser.setCreateTime(new Date().getTime());
        jdzcUser.setLastLoginTime(new Date().getTime());
        jdzcUser.setPhone(phone);
        jdzcUserMapper.addWxUser(jdzcUser);
        return jdzcUser;
    }

    @Override
    public Integer updateWxUserLastLoginTime(Integer wxUserId, long time) {
        return jdzcUserMapper.updateWxUserLastLoginTime(wxUserId, time);
    }

    @Override
    public String createLoginToken(Integer wxUserId) {
        String token = Tools.getRamdomStr();
        redisService.setKey(token, String.valueOf(wxUserId), Constant.WX_XCX_TOKEN_EXPIRE, TimeUnit.DAYS);
        return token;
    }

    @Override
    public List<Map<String, Object>> getUserStudentList(Integer userId) {
        List<Map<String, Object>> userStudentList = jdzcUserMapper.getUserStudentList(userId);
        if (userStudentList != null && userStudentList.size() > 0) {
            for (Map<String, Object> map : userStudentList) {
                if (map.containsKey("imei")) {
                    String imei = (String) map.get("imei");
                    if(StringUtils.isNotBlank(imei)){
                        boolean b = deviceOnline((String) map.get("imei"));
                        map.put("start", b ? "在线" : "离线");
                    }else {
                        map.put("start","未绑定设备");
                    }
                }
            }
        }
        return userStudentList;
    }

    @Override
    public RespEntity bindingStudent(Integer userId, String imei, String name, String studetnNo) {
        // 1. 校验三个参数
        DeviceInfo deviceInfo = jdDeviceInfoMapper.getDeviceInfoByImei(imei);
        if (deviceInfo == null) {
            return new RespEntity(RespCode.DEVICE_NOT_FOUND);
        }
        if (deviceInfo.getDeviceType() != Constant.PLATFORM_DEVICE) {
            return new RespEntity(RespCode.NOT_PLATFORM_DEVICE_CANNOT_BIND);
        }
        Integer studentId = deviceInfo.getStudentId();
        if (studentId == null) {
            return new RespEntity(RespCode.STUDENT_MSG_ERROR);
        }
        Student student = jdzcStudentMapper.getStudentInfoById(studentId);
        if (student == null) {
            return new RespEntity(RespCode.STUDENT_MSG_ERROR);
        }
        // 名字学号都一样，才进行修改
        if (studetnNo.equals(student.getStudentNo()) && name.equals(student.getStudentName())) {
            // 防止重复绑定
            JdzcUserStudentPermission wxUserStudentPermission = jdzcUserStudentPermissionMapper.getWxUserStudentPermissionByCondition(studentId, userId);
            if (wxUserStudentPermission == null) {
                //获取学生的绑定列表
                List<Map<String, Object>> list = jdzcStudentMapper.bindStudentPhoneList(studentId);
                Integer isMan = 0;
                Integer isAuthority = 0;
                if (list == null || list.size() == 0) {
                    //将该用户设置为管理员并处于授权状态
                    isMan = 1;
                    isAuthority = 1;
                }
                //获取微信用户的手机号码
                JdzcUser wxUser = jdzcUserMapper.getWxUserById(userId);
                jdzcUserStudentPermissionMapper.addWxUserStudentPermission(wxUser.getPhone(), studentId, userId, isMan, isAuthority);
                // 更新学生表绑定微信的状态
                jdzcStudentMapper.updateStudentWxUserBindStatus(1, studentId);
            }
            //如若是喜马拉雅的设备则下发绑定关系指令
            if (!StringUtils.isBlank(deviceInfo.getOrgCode()) && deviceInfo.getOrgCode().contains("A01A03A05")) {
                //设备在线则进行发送
                //根据学生id获取年级、班级、学生名称、学校名称
                Map<String, Object> bindingMap = jdzcStudentMapper.getStuBindingMessByStuId(deviceInfo.getStudentId());
                bindingMap.put("imei", imei);
                bindingMap.put("status", Constant.DEVICE_BINDING);
                bindingMap.put("commandNumber", getCurTime());
                String s = JSONObject.toJSONString(bindingMap);
                boolean isOnline = deviceOnline(imei);
                //进行指令下发
                commandSendUtils.sendBindingStatus(JSONObject.parseObject(s), Constant.WX_COMMAND_USER_ID, isOnline, false);
            }
            return new RespEntity(RespCode.SUCCESS);
        }
        return new RespEntity(RespCode.STUDENT_MSG_ERROR);
    }

    @Override
    public Map<String, Object> getBindingById(Integer id) {
        return jdzcUserStudentPermissionMapper.getBindingById(id);
    }

    @Override
    public Integer changeManger(Integer stuId, Integer userId, Integer transferUserId) {
        //将之前的用户设置为非管理员
        Integer i = jdzcUserStudentPermissionMapper.changeManager(userId, 0, stuId, 1);
        //将现在用户设置为管理员
        Integer i1 = jdzcUserStudentPermissionMapper.changeManager(transferUserId, 1, stuId, 1);
        return i + i1;
    }


    /**
     * 判断设备是否在线
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    public boolean deviceOnline(String imei) {
        boolean isOnline = redisService.hasKey(Constant.DEVICE_ONLINE_PREFIX + imei);
        return isOnline;
    }

    @Override
    public Integer changeAuthority(Integer id, Integer status) {
        return jdzcUserStudentPermissionMapper.giveAuthority(id, status);
    }

    @Override
    public int modifyPhoneByImei(String imei, String phone) {
        return jdDeviceInfoMapper.modifyPhoneByImei(imei, phone);
    }

    @Override
    public JdzcUser getWxUserById(Integer userId) {
        return jdzcUserMapper.getWxUserById(userId);
    }

    @Override
    public String getClassesMessByUserId(Integer userId) {
        return teacherMapper.getClassesMessByUserId(userId);
    }

    @Override
    public List<Map<String, Object>> getClassNameByClassIdList(List<Integer> classIdList) {
        return teacherMapper.getClassNameByClassIdList(classIdList);
    }

    @Override
    public List<Map<String, Object>> getOpenIdAndStuNameListByClassId(Integer classId) {
        return jdzcUserMapper.getOpenIdAndStuNameListByClassId(classId);
    }

}
